package com.csdn.leon.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.csdn.leon.adapter.BlogAdapter;
import com.csdn.leon.adapter.CloumnAdapter;
import com.csdn.leon.anima.AnimatorUtil;
import com.csdn.leon.base.ListBaseAdapter;
import com.csdn.leon.fragment.HomeFragment.ParserTask;
import com.csdn.leon.interf.ActivityListener;
import com.csdn.leon.model.CloumnModel;
import com.csdn.leon.net.CSDNapi;
import com.csdn.leon.refresh.PullToRefreshView;
import com.csdn.leon.refresh.PullToRefreshView.OnRefreshListener;
import com.csdn.leon.util.JsoupUtil;
import com.csdn.leon.util.URLUtil;
import com.csdn.leon.view.EmptyLayout;
import com.csdn.leon.view.popup.FloatPopupWindow;
import com.loopj.android.http.TextHttpResponseHandler;
import com.csdn.leon.base.R;

public class SpecialCloumnFragment extends BaseFragment implements
		OnRefreshListener, OnScrollListener {

	private final String TAG = SpecialCloumnFragment.class.getSimpleName();
	public final static String TITLE = "首页";
	public static final int REFRESH_DELAY = 2000;
	private static int blogType;
	protected int mCurrentPage = 1;

	protected String url;
	private PullToRefreshView mPullToRefreshView;
	Map<String, Integer> map;
	private CloumnAdapter blogAdapter;
	private ListView listView;
	private View view;
	private Activity activity;
	@InjectView(R.id.list_view)
	protected ListView mListView;
	@InjectView(R.id.error_layout)
	protected EmptyLayout mErrorLayout;
	private ParserTask mParserTask;
	private ActivityListener activityListener;
	private ImageView floatBtn;

	int touchSlop = 10;
	private boolean isNew = true;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);// 保留fragment对象
	}

	/*
	 * 返回View
	 * 
	 * @see
	 * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
	 * android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		ButterKnife.inject(this, view);
		view = inflater
				.inflate(R.layout.home_fragment_layout, container, false);

		initView();

		onRefresh();
		return view;
	}

	private void initView() {
		floatBtn = (ImageView) view.findViewById(R.id.float_btn);
		floatBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				FloatPopupWindow pop = new FloatPopupWindow(activity, v);

			}
		});
		blogAdapter = new CloumnAdapter(activity);
		listView = (ListView) view.findViewById(R.id.list_view);
		mErrorLayout = (EmptyLayout) view.findViewById(R.id.error_layout);
		listView.setAdapter(blogAdapter);
		listView.setOnScrollListener(this);
		mPullToRefreshView = (PullToRefreshView) view
				.findViewById(R.id.pull_to_refresh);
		mPullToRefreshView.setOnRefreshListener(this);
		mState = STATE_NONE;
		mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mCurrentPage = 1;
				mState = STATE_REFRESH;
				mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
				requestData(true);
			}
		});
	}

	@Override
	public void onRefresh() {
		mCurrentPage = 1;
		sendRequestData(blogType, true);
		mPullToRefreshView.setRefreshing(true);
		mState = STATE_REFRESH;
		listView.setSelection(0);
	}

	TextHttpResponseHandler handle = new TextHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2,
				Throwable arg3) {
			mPullToRefreshView.setRefreshing(false);
			Toast.makeText(activity, "加载失败，请重新加载...", 2000).show();
			// mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
			if (activityListener != null) {
				activityListener.completedRefresh();
			}
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String s) {
			Log.w("dd", s);
			executeParserTask(s);

		}
	};

	/***
	 * 获取列表数据
	 * 
	 * 
	 * @author leon
	 * 
	 * @return void
	 * @param refresh
	 */
	// 取新的数据
	protected void requestData(boolean refresh) {

		sendRequestData(blogType, refresh);
	}

	protected void sendRequestData(int type, boolean flag) {
		if (activityListener != null) {
			activityListener.startRefresh();
		}
		if (flag) {

			url = URLUtil.getClumnsBlogListURL(type);
		} else {
			url = URLUtil.getClumnsBlogListURL(blogType,
					String.valueOf(mCurrentPage));
		}
		Log.w(TAG, url);
		CSDNapi.getBlogList(url, handle);
	}

	private void executeParserTask(String data) {
		cancelParserTask();
		mParserTask = new ParserTask(data);
		mParserTask.execute();
	}

	private void cancelParserTask() {
		if (mParserTask != null) {
			mParserTask.cancel(true);
			mParserTask = null;
		}
	}

	class ParserTask extends AsyncTask<Void, Void, String> {

		private final String reponseData;
		private boolean parserError;
		private List<CloumnModel> list;

		public ParserTask(String data) {
			this.reponseData = data;
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				list = paraseToList(reponseData);

			} catch (Exception e) {
				e.printStackTrace();

				parserError = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			blogAdapter.setState(ListBaseAdapter.STATE_LOAD_MORE);
			executeOnLoadDataSuccess(list);
			executeOnLoadFinish();
			if (activityListener != null) {
				activityListener.completedRefresh();
			}
		}
	}

	// 完成刷新
	protected void executeOnLoadFinish() {
		mPullToRefreshView.setRefreshing(false);
		mState = STATE_NONE;
	}

	/**
	 * 
	 * 方法名称: paraseToList 功能描述: 解析成List<CloumnModel>. 修改记录: 修改者: lenovo 修改日期:
	 * 2015年5月21日 修改内容: TODO(描述本次修改内容).
	 * 
	 * @param data
	 * @return
	 */
	public List<CloumnModel> paraseToList(String data) {
		List<CloumnModel> list = JsoupUtil.getClumnsBlogList(data);
		return list;
	}

	protected void executeOnLoadDataSuccess(List<CloumnModel> data) {
		if (data == null) {
			data = new ArrayList<CloumnModel>();
		}
		if (mCurrentPage == 1) {
			blogAdapter.clear();
		}
		mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
		int adapterState = ListBaseAdapter.STATE_EMPTY_ITEM;
		if (data.size() == 1) {

		}
		// blogAdapter.setState(adapterState);
		blogAdapter.addList(data);
		// 判断等于是因为最后有一项是listview的状态
		if (blogAdapter.getCount() == 1) {
			if (needShowEmptyNoData()) {
				mErrorLayout.setErrorType(EmptyLayout.NODATA);
			} else {
				blogAdapter.setState(ListBaseAdapter.STATE_EMPTY_ITEM);
				blogAdapter.notifyDataSetChanged();
			}
		}
	}

	private boolean needShowEmptyNoData() {
		return true;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (scrollFlag) {
			AnimatorUtil.animateHide(floatBtn);
		} else {
			AnimatorUtil.animateBack(floatBtn);
		}
		lastPosition = firstVisibleItem;
	}

	boolean scrollFlag = false;

	/**
	 * 滑动到底部时是否更新 (non-Javadoc)
	 * 
	 * @see android.widget.AbsListView.OnScrollListener#onScrollStateChanged(android.widget.AbsListView,
	 *      int)
	 */
	int lastPosition = 0;
	int state = AbsListView.OnScrollListener.SCROLL_STATE_IDLE;

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		Log.w("是否到底部", "scrollState:" + scrollState);
		state = scrollState;
		if (blogAdapter == null || blogAdapter.getCount() == 0) {
			return;
		}
		// 数据已经全部加载，或数据为空时，或正在加载，不处理滚动事件
		if (mState == STATE_LOADMORE || mState == STATE_REFRESH) {
			return;
		}
		// 判断是否滚动到底部
		boolean scrollEnd = false;
		try {
			if (view.getPositionForView(blogAdapter.getFooterView()) == view
					.getLastVisiblePosition())
				scrollEnd = true;
		} catch (Exception e) {
			scrollEnd = false;
		}
		if (mState == STATE_NONE && scrollEnd) {
			int state = blogAdapter.getState();
			if (blogAdapter.getState() == ListBaseAdapter.STATE_LOAD_MORE
					|| blogAdapter.getState() == ListBaseAdapter.STATE_NETWORK_ERROR) {
				mCurrentPage++;
				Log.w(TAG, "mCurrentPage:" + mCurrentPage);
				mState = STATE_LOADMORE;
				requestData(false);
				blogAdapter.setFooterViewLoading();
			}
		}
		// TODO Auto-generated method stub
		switch (scrollState) {
		// 当不滚动时
		case OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
			scrollFlag = false;
			AnimatorUtil.animateBack(floatBtn);
			// 判断滚动到底部
			if (listView.getLastVisiblePosition() == (listView.getCount() - 1)) {
				// toTopBtn.setVisibility(View.VISIBLE);
			}
			// 判断滚动到顶部
			if (listView.getFirstVisiblePosition() == 0) {
				// toTopBtn.setVisibility(View.GONE);
			}

			break;
		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
			scrollFlag = true;
			break;
		case OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
			scrollFlag = true;
			break;
		}
	}

	public ActivityListener getActivityListener() {
		return activityListener;
	}

	public void setActivityListener(ActivityListener activityListener) {
		this.activityListener = activityListener;
	}

	public boolean isNew() {
		return isNew;
	}

	public void setNew(boolean isNew) {
		this.isNew = isNew;
	}
}
